﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data;
using FreedomERP.Comm;
using FreedomERP.Comm.Utils;
using FreedomERP.Comm.DB;
using FreedomERP.Models;
using FreedomERP.Models.Bd;

namespace FreedomERP.Dao.Bd.Impl
{
    /// <summary>
    /// 客户数据层实现类
    /// 作者：姚少鹏
    /// </summary>
    public class BdCustomerDaoImpl : IBdCustomerDao
    {
        FreedomERPEntities dbEntities = new FreedomERPEntities();

        /// <summary>
        /// 根据FId获取客户
        /// </summary>
        /// <param name="FId"></param>
        /// <returns></returns>
        public BdCustomer getCustomerByFId(string FId)
        {
            BdCustomer obj = null;

            List<BdCustomer> customerList = (from ba in dbEntities.BdCustomer where ba.FId == FId select ba).ToList<BdCustomer>();
            if (customerList != null && customerList.Count > 0)
                obj = customerList.First();

            return obj;
        }

        /// <summary>
        /// 根据名称获取客户
        /// </summary>
        /// <param name="FName"></param>
        /// <returns></returns>
        public BdCustomer getCustomerByFName(string FName)
        {
            BdCustomer obj = null;

            List<BdCustomer> customerList = (from ba in dbEntities.BdCustomer where ba.FName.Equals(FName) select ba).ToList<BdCustomer>();
            if (customerList != null && customerList.Count > 0)
                obj = customerList.First();

            return obj;
        }

        /// <summary>
        /// 查找客户列表
        /// 作者：陈新杰
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <param name="totalCount">数据库客户总数量，用于分页</param>
        /// <returns></returns>
        public DAOResult<BdCustomer> findCustomerList(CustomerParameters param, out int totalCount)
        {
            DAOResult<BdCustomer> daoResult = null;
            Expression<Func<BdCustomer, bool>> predicate = PredicateExtensions.True<BdCustomer>();
            if (param.FId != null && ConstData.EMPTY_STRING != param.FId)
            {
                predicate = predicate.And(customer => customer.FId.Contains(param.FId));
            }
            if (param.FNumber != null && ConstData.EMPTY_STRING != param.FNumber)
            {
                predicate = predicate.And(customer => customer.FNumber.Contains(param.FNumber));
            }
            if (param.FName != null && ConstData.EMPTY_STRING != param.FName)
            {
                predicate = predicate.And(customer => customer.FName.Contains(param.FName));
            }
            if (param.FCreatorId != null && ConstData.EMPTY_STRING != param.FCreatorId)
            {
                predicate = predicate.And(customer => customer.FCreatorId.Contains(param.FCreatorId));
            }


            if (param.FModifierId != null && ConstData.EMPTY_STRING != param.FModifierId)
            {
                predicate = predicate.And(customer => customer.FModifierId.Contains(param.FModifierId));
            }

            if (param.FOrgunitId != null && ConstData.EMPTY_STRING != param.FOrgunitId)
            {
                predicate = predicate.And(customer => customer.FOrgunitId.Contains(param.FOrgunitId));
            }
            if (param.FContactAddress != null && ConstData.EMPTY_STRING != param.FContactAddress)
            {
                predicate = predicate.And(customer => customer.FContactAddress.Contains(param.FContactAddress));
            }
            if (param.FContactEmail != null && ConstData.EMPTY_STRING != param.FContactEmail)
            {
                predicate = predicate.And(customer => customer.FContactEmail.Contains(param.FContactEmail));
            }
            if (param.FContactMobile != null && ConstData.EMPTY_STRING != param.FContactMobile)
            {
                predicate = predicate.And(customer => customer.FContactMobile.Contains(param.FContactMobile));
            }
            if (param.FContactor != null && ConstData.EMPTY_STRING != param.FContactor)
            {
                predicate = predicate.And(customer => customer.FContactor.Contains(param.FContactor));
            }
            if (param.FContactPhone != null && ConstData.EMPTY_STRING != param.FContactPhone)
            {
                predicate = predicate.And(customer => customer.FContactPhone.Contains(param.FContactPhone));
            }
            predicate = predicate.And(customer => customer.FOrgunitId.Equals(param.FOrgunitId));
            predicate = predicate.And(customer => customer.FStatusId.Equals(param.fStatusID));
            var query = dbEntities.BdCustomer.Where(predicate);
            totalCount = query.Count();
            List<BdCustomer> customers = query.OrderByDescending(prod => prod.FModifyTime).Skip(param.start).Take(param.limit).ToList();
            daoResult = new DAOResult<BdCustomer>(true, null, customers);
            return daoResult;
        }

        public DAOResult<String> saveOrUpdateCustomer(BdCustomerView customer)
        {
            DAOResult<String> daoResult = null;
            bool isNew = false;
            String FID = customer.FId;
            String ForgunitID = customer.FOrgunitId;
            if (ForgunitID != null && !ConstData.EMPTY_STRING.Equals(ForgunitID))
            {
                IBdOrgunitDao orgDao = new BdOrgunitDaoImpl();
                BdOrgunit orgunit = orgDao.findOrgunitById(ForgunitID);
                if (orgunit == null)
                {
                    return new DAOResult<string>(false, "找不到商户信息，无法添加客户信息。", null);
                }
            }
            else
            {
                return new DAOResult<string>(false, "商户信息参数为空，无法添加客户信息。", null);
            }
            String statusId = null;
            IBdCategoryDao cateDao = new BdCategoryDaoImpl();
            statusId = cateDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_CUSTOMER_STATUS_TYPE, ConstData.CUSTOMER_STATUS_YES);
            if (statusId == null || ConstData.EMPTY_STRING.Equals(statusId))
            {
                return new DAOResult<string>(false, "客户状态元数据信息不存在，无法删除数据", null);
            }

            BdCustomer bdCustomer = null;
            if (FID == null)//新增客户
            {
                isNew = true;
                List<String> ifCustomerNumbers = (from ifCustomer in dbEntities.BdCustomer where ifCustomer.FNumber == customer.FNumber && ifCustomer.FStatusId == statusId select ifCustomer.FNumber).ToList<String>();
                if (ifCustomerNumbers.Count > 0)
                {
                    return new DAOResult<String>(false, "该客户编号已存在，无法保存。", null);
                }
                FID = GuidUtils.getGuid();
                bdCustomer = new BdCustomer();
                String creatorID = customer.FCreatorId;

                if (creatorID != null && !ConstData.EMPTY_STRING.Equals(creatorID))
                {
                    BdAccount creator = null;
                    IBdAccountDao acctDao = new BdAccountDaoImpl();
                    creator = acctDao.GetAccountByFId(creatorID);
                    if (creator == null)
                    {
                        return new DAOResult<string>(false, "找不到添加者信息，无法添加客户信息。", null);
                    }
                }
                String modefierID = customer.FModifierId;
                if (modefierID != null && !ConstData.EMPTY_STRING.Equals(modefierID))
                {
                    BdAccount modefier = null;
                    IBdAccountDao acctDao = new BdAccountDaoImpl();
                    modefier = acctDao.GetAccountByFId(modefierID);
                    if (modefier == null)
                    {
                        return new DAOResult<string>(false, "找不到修改者信息，无法添加客户信息。", null);
                    }
                }

                bdCustomer.FId = FID;
                bdCustomer.FModifierId = modefierID;
                bdCustomer.FCreatorId = creatorID;
                bdCustomer.FCreateTime = customer.FCreateTime;
                bdCustomer.FModifyTime = customer.FModifyTime;
                bdCustomer.FNumber = customer.FNumber;

            }
            else//更新客户
            {

                String modefierID = customer.FModifierId;
                if (modefierID != null && !ConstData.EMPTY_STRING.Equals(modefierID))
                {
                    BdAccount modefier = null;
                    IBdAccountDao acctDao = new BdAccountDaoImpl();
                    modefier = acctDao.GetAccountByFId(modefierID);
                    if (modefier == null)
                    {
                        return new DAOResult<string>(false, "找不到修改者信息，无法添加客户信息。", null);
                    }
                }
                List<BdCustomer> customers = (from cust in dbEntities.BdCustomer where cust.FId.Equals(FID) select cust).ToList();
                if (customers.Count <= 0)
                {
                    return new DAOResult<String>(false, "客户信息不存在，无法修改", null);
                }
                else
                {
                    bdCustomer = customers.First();
                }
                if (customer.FNumber != null && (bdCustomer.FNumber != customer.FNumber))
                {
                    return new DAOResult<String>(false, "客户编号无法修改，保存失败", null);
                }
            }

            bdCustomer.FModifierId = customer.FModifierId;
            bdCustomer.FModifyTime = customer.FModifyTime;
            bdCustomer.FName = customer.FName;

            bdCustomer.FContactAddress = customer.FContactAddress;
            bdCustomer.FContactEmail = customer.FContactEmail;
            bdCustomer.FContactor = customer.FContactor;
            bdCustomer.FContactPhone = customer.FContactPhone;
            bdCustomer.FContactMobile = customer.FContactMobile;
            bdCustomer.FOrgunitId = customer.FOrgunitId;
            bdCustomer.FStatusId = statusId;
            if (isNew)
            {
                dbEntities.BdCustomer.AddObject(bdCustomer);
            }
            dbEntities.SaveChanges();
            List<String> resultSet = new List<String>();
            resultSet.Add(FID);
            daoResult = new DAOResult<String>(true, null, resultSet);
            return daoResult;
        }

        /// <summary>
        /// 根据客户ID删除客户信息
        /// </summary>
        /// <param name="FID"></param>
        /// <returns></returns>
        public DAOResult<String> deleteCustomer(String FID)
        {
            BdCustomer bdCustomer = null;
            List<BdCustomer> customers = (from cust in dbEntities.BdCustomer where cust.FId.Equals(FID) select cust).ToList();

            if (customers.Count <= 0)
            {
                return new DAOResult<String>(false, "客户信息不存在，无法删除", null);
            }
            else
            {
                bdCustomer = customers.First();
            }

            List<InvSendOrder> sendOrders = (from sendOrd in dbEntities.InvSendOrder where (sendOrd.FCustomerId == bdCustomer.FId && sendOrd.BdCategory.FType == ConstData.CATEGORY_SEND_ORDER_STATUS && (sendOrd.BdCategory.FNumber == ConstData.CATEGORY_SEND_ORDER_STATUS_SAVE || sendOrd.BdCategory.FNumber == ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE)) select sendOrd).ToList();
            if (sendOrders.Count > 0)
            {
                return new DAOResult<String>(false, "该客户信息在送货单中被引用，无法删除", null);
            }
            String statusId = null;
            IBdCategoryDao cateDao = new BdCategoryDaoImpl();
            statusId = cateDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_CUSTOMER_STATUS_TYPE, ConstData.CUSTOMER_STATUS_NO);
            if (statusId == null || ConstData.EMPTY_STRING.Equals(statusId))
            {
                return new DAOResult<string>(false, "客户状态元数据信息不存在，无法删除数据", null);
            }
            bdCustomer.FStatusId = statusId;
            dbEntities.SaveChanges();
            return new DAOResult<string>(true, null, null);

        }
    }



}
